package org.nvframe.component.action;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Vector2f;
import org.nvframe.component.AbstractComponent;
import org.nvframe.component.physics.motion.ToDirectionMotion;
import org.nvframe.component.state.Position;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.UpdateEvent;
import org.nvframe.event.eventtype.UpdateListener;
import org.nvframe.exception.NVFrameException;
import org.nvframe.factory.EntityFactory;
import org.nvframe.util.Settings;

/**
 * 
 * @author Nik Van Looy
 */
public class ShootAction extends AbstractComponent implements UpdateListener {
	
	protected String bulletId;
	
	public ShootAction(String id, Entity owner, Settings settings) throws NVFrameException {
		super(id, owner);
		
		bulletId = settings.getString("bulletEntityId", null);
		
		EventService.getInstance().addEventListener(this);
	}

	@Override
	public void onUpdate(UpdateEvent event) {
		GameContainer gc = event.getGc();
		
		Input input = gc.getInput();
		
		if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
			Vector2f targetCoords = new Vector2f(input.getMouseX(), input.getMouseY());

			try {
				// create the bullet entity
				Entity entity = EntityFactory.getInstance().getEntityFromPrototype(bulletId);
				
				Position position = (Position) owner.getComponent(Position.class);

				ToDirectionMotion entityMotionComp = (ToDirectionMotion) entity.getComponent(ToDirectionMotion.class);
				entityMotionComp.startMotion(position.getXY().copy(), targetCoords.copy());
			} 
			catch(NVFrameException ee) {
				ee.printStackTrace();
			}
		}
	}
	
	@Override
	public void removed(Entity entity) {
		EventService.getInstance().removeEventListener(this);
	}
}
